package com.obor.quartz.job;

import java.util.Map.Entry;
import java.util.Set;

import org.quartz.CronScheduleBuilder;
import org.quartz.DateBuilder;
import org.quartz.DateBuilder.IntervalUnit;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerContext;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;

/**
 * 
 * @Company OBOR
 * @Author 周楠
 * @Description 2019年4月2日
 *
 */

public class JobManager  {
	
	private Scheduler scheduler;
	
	public Scheduler getScheduler() {
		return scheduler;
	}

	public void setScheduler(Scheduler scheduler) {
		this.scheduler = scheduler;
	}


	@SuppressWarnings("unchecked")
	public void addJob(JobInfo job) {
		try {

			Class<? extends Job> jobClass = (Class<? extends Job>) (Class.forName(job.getBeanClass()));

			JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(job.getKey(), job.getGroup())
					.build();
			
			jobDetail.getJobDataMap().put("info", job);

			// 定义调度触发规则
			// 使用cornTrigger规则
			Trigger trigger = TriggerBuilder.newTrigger().withIdentity(job.getKey(), job.getGroup())// 触发器key
					.startAt(DateBuilder.futureDate(1, IntervalUnit.SECOND))
					.withSchedule(CronScheduleBuilder.cronSchedule(job.getCronExpression())).startNow().build();
	
			
			scheduler.scheduleJob(jobDetail, trigger);
			
			// 启动
			if (!scheduler.isShutdown()) {
				scheduler.start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void schedulerStart() throws SchedulerException {

		scheduler.start();

	}

	public void delJob(String jobKey, String group) throws SchedulerException {

		scheduler.deleteJob(new JobKey(jobKey, group));

	}

	public void pauseJob(String jobKey, String group) throws SchedulerException {

		scheduler.pauseTrigger(new TriggerKey(jobKey, group));

	}

	public void resumeJob(String jobKey, String group) throws SchedulerException {

		scheduler.resumeTrigger(new TriggerKey(jobKey, group));

	}

	public void schedulerContext(String jobKey) throws SchedulerException {

		SchedulerContext sc = scheduler.getContext();
		
		Set<Entry<String, Object>> scSet= sc.entrySet();
		
		for (Entry<String, Object> entry : scSet) {
			
			Object ob= entry.getValue();
			
			System.out.println(ob);
			
		}

	}

}